using System;
using System.Xml;

namespace BoxBinary.AspectCache.Core.Helpers
{
    /// <summary>
    /// Provides helper methods for dealing with Xml
    /// </summary>
    public static class Xml
    {
        /// <summary>
        /// Gets an <see cref="XmlAttribute"/> from an <see cref="XmlNode"/>
        /// </summary>
        /// <param name="attributeName"></param>
        /// <param name="xmlNode"></param>
        /// <returns></returns>
        public static XmlAttribute GetAttributeFromXmlNode(string attributeName, XmlNode xmlNode)
        {
            if (xmlNode.Attributes != null)
            {
                foreach (XmlAttribute attribute in xmlNode.Attributes)
                {
                    if (string.Compare(attribute.Name, attributeName, StringComparison.InvariantCultureIgnoreCase) == 0)
                        return attribute;
                }
            }
            return null;
        }

        /// <summary>
        /// Gets a string attribute value from an <see cref="XmlNode"/>
        /// </summary>
        /// <param name="attributeName"></param>
        /// <param name="xmlNode"></param>
        /// <returns></returns>
        public static string GetAttributeValueFromXmlNode(string attributeName, XmlNode xmlNode)
        {
            XmlAttribute xAttr = GetAttributeFromXmlNode(attributeName, xmlNode);
            if (xAttr != null)
                return xAttr.Value;
            else
                return string.Empty;
        }

        /// <summary>
        /// Sets an attribute's string value on an <see cref="XmlNode"/>
        /// </summary>
        /// <param name="xmlNode"></param>
        /// <param name="attributeName"></param>
        /// <param name="value"></param>
        public static void SetAttribute(XmlNode xmlNode, string attributeName, string value)
        {
            XmlAttribute xAttr = GetAttributeFromXmlNode(attributeName, xmlNode);
            if (xAttr != null)
                xAttr.Value = value;
        }
    }
}